const Router = require("koa-router");
const router = new Router();
const jwt = require("jsonwebtoken");
const {
  userLogin,
  getUserInfo,
  addToCart,
  getCartList,
  removeFromCart,
  getCartCount,
} = require("../controllers/index.js");
const { sign } = require("../utils/jwt.js");

// 登录接口
router.post("/login", async (ctx, next) => {
  const { username, password } = ctx.request.body; // post请求的数据

  try {
    const res = await userLogin(username, password);
    console.log(res);

    if (res.length) {
      // 账号密码正确
      const data = {
        username: res[0].username,
        id: res[0].id,
        avatar: res[0].avatar,
      };
      const token = sign({
        id: res[0].id,
        username: res[0].username,
      });

      ctx.body = {
        code: 200,
        data: data,
        token: token,
        msg: "登录成功",
      };
    } else {
      ctx.body = {
        code: 500,
        msg: "账号或密码错误",
      };
    }
  } catch (error) {
    console.log(error);

    ctx.body = {
      code: 500,
      data: error,
      msg: "服务器异常",
    };
  }
});

// 获取用户信息
router.get("/user/info", async (ctx, next) => {
  try {
    const token = ctx.headers.authorization;
    
    if (!token) {
      ctx.body = {
        code: 401,
        msg: "请先登录",
        data: null,
      };
      return;
    }

    try {
      const decoded = jwt.verify(token, "abc"); // 直接使用完整token
      const userId = decoded.id;
      const userInfo = await getUserInfo(userId);
      ctx.body = {
        code: 200,
        data: userInfo[0], // 返回查询到的用户信息
        msg: "获取成功",
      };
    } catch (err) {
      ctx.body = {
        code: 401,
        data: null,
        msg: "token无效",
      };
    }
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 500,
      msg: "获取失败",
    };
  }
});

// 添加到购物车
router.post("/cart/add", async (ctx) => {
  const { frameId, frameType } = ctx.request.body;
  console.log(frameId, frameType);
  
  const token = ctx.headers.authorization;

  if (!token) {
    ctx.body = {
      code: 401,
      msg: "请先登录",
    };
    return;
  }

  const userId = jwt.verify(token, "abc").id; // 使用密钥解码token并获取用户ID
  
  if (!userId) {
    ctx.body = {
      code: 401,
      msg: "用户未登录",
    };
    return;
  }

  try {
    await addToCart(userId, frameId, frameType);
    console.log(userId, frameId, frameType);
    
    ctx.body = {
      code: 200,
      msg: "添加成功",
    };
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 500,
      msg: "添加失败",
    };
  }
});

// 获取购物车列表
router.get("/cart/list", async (ctx) => {
  const userId = ctx.state.user ? ctx.state.user.id : null; // 从token中获取用户id
  if (!userId) {
    ctx.body = {
      code: 401,
      msg: "用户未登录",
    };
    return;
  }

  try {
    const cartItems = await getCartList(userId);
    ctx.body = {
      code: 200,
      data: cartItems,
      message: "获取购物车列表成功",
    };
  } catch (error) {
    console.error("获取购物车列表错误:", error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "服务器错误",
      error: error.message,
    };
  }
});

// 从购物车中删除商品
router.delete("/cart/remove/:id", async (ctx, next) => {
  const cartId = ctx.params.id;
  const userId = ctx.state.user ? ctx.state.user.id : null;
  if (!userId) {
    ctx.body = {
      code: 401,
      msg: "用户未登录",
    };
    return;
  }

  try {
    await removeFromCart(cartId, userId);
    ctx.body = {
      code: 200,
      msg: "删除成功",
    };
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 500,
      msg: "删除失败",
    };
  }
});

// 获取购物车商品数量
router.get("/cart/count", async (ctx, next) => {
  const userId = ctx.state.user ? ctx.state.user.id : null;
  if (!userId) {
    ctx.body = {
      code: 401,
      msg: "用户未登录",
    };
    return;
  }

  try {
    const count = await getCartCount(userId);
    ctx.body = {
      code: 200,
      data: count,
      msg: "获取成功",
    };
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 500,
      msg: "获取失败",
    };
  }
});

module.exports = router;
